package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j

public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    MongoTemplate mongoTemplate;


    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //1.校验参数判断从线程中获取的用户是否为空
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "该操作需要登录账号");
        }
        //2.查询实体行为
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        //2.判断实体行为是否存在
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "又查询到该实体行为");
        }
        //3.判断该用户是否有点赞行为，若有  不必重复点赞
        Query query = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()).and("articleId").is(dto.getArticleId()));
        ApLikesBehavior likesBehavior = mongoTemplate.findOne(query, ApLikesBehavior.class);
        //3.1判断用户是否重复点赞
        if (likesBehavior != null && dto.getOperation().intValue() == 0) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "请勿重复点赞");
        }
        //4.点赞  取消点赞  添加和删除  点赞数据
        //4.1  点赞添加数据（将被点赞的文章ID存入点赞列表中）
        //4.1.1 先判断获取到的行为参数  为0  则添加数据到ApLikesBehavior
        if (dto.getOperation().intValue() == 0) {
            likesBehavior = new ApLikesBehavior();
            likesBehavior.setEntryId(apBehaviorEntry.getId());
            likesBehavior.setArticleId(dto.getArticleId());
            likesBehavior.setType((short) 0);
            likesBehavior.setOperation((short) 0);
            likesBehavior.setCreatedTime(new Date());
            mongoTemplate.save(likesBehavior);
            //4.2取消点赞  从表中删除对应信息
        } else {
            mongoTemplate.remove(query, ApLikesBehavior.class);
        }
        return ResponseResult.okResult();

    }
}
